<?php

namespace app\hook;

use Illuminate\Database\Capsule\Manager as DB;

class userregister
{
    public function successed($params = [])
    {
        $member = $params['member'];
        $inviter = $params['inviter'];

        // 邀请人奖励
        $reward_score = DB::table('sys_config')
            ->where('type', 18)
            ->where('key', 'recommend_score')
            ->value('value') ?: 0;
        if ($reward_score) {
            \memberModel::score($reward_score, $inviter, 'share', 0, '邀请用户获得积分 受邀用户id:' . $member->id);
        }

        // 记录团队关系邀请人邀请人
        $to_insert = [['member_id' => $inviter->id, 'level' => 1, 'children_id' => $member->id]];
        \memberchildrenModel::where('children_id', $inviter->id)
            ->select(['member_id', 'level', 'member_id'])
            ->orderBy('level')
            ->chunk(500, function($items) use ($member, &$to_insert) {
                foreach ($items as $item) {
                    $to_insert[] = [
                        'member_id' => $item->member_id,
                        'level' => $item['level'] + 1,
                        'children_id' => $member->id,
                    ];
                }
                \memberchildrenModel::insertOrIgnore($to_insert);
                $to_insert = [];
            });
        if (!empty($to_insert)) {
            \memberchildrenModel::insertOrIgnore($to_insert);
        }
        \Log::out('用户注册成功，记录团队关系，奖励邀请人', 'hook');

        $id = $member->id;
        $tkLevel = \tuikelevelModel::orderBy('level', 'ASC')->value('level');
        $tgLevel = \twostagelevelModel::orderBy('level', 'ASC')->value('level');
        DB::transaction(function() use($id, $tkLevel, $tgLevel){
            $row = [
                'tuike_id'   => $id,
                'level'      => $tkLevel,
                'created_at' => date('Y-m-d H:i:s')
            ];
            \tuikeModel::insert($row);
            $log = [
                'tuike_id'   => $id,
                'event'      => 'signin',
                'after'      => $tkLevel,
                'remark'     => '用户注册后自动设置用户为推客，等级为：' . $tkLevel,
                'oper_type'  => 'user',
                'oper_id'    => $id,
                'created_at' => date('Y-m-d H:i:s')
            ];
            \tuikelogModel::insert($log);

            $row = [
                'twostage_id'=> $id,
                'level'      => $tgLevel,
                'created_at' => date('Y-m-d H:i:s')
            ];
            \twostageModel::insert($row);
            $log = [
                'twostage_id'=> $id,
                'event'      => 'signin',
                'after'      => $tgLevel,
                'remark'     => '用户注册后自动设置用户为推广大使，等级为：' . $tgLevel,
                'oper_type'  => 'user',
                'oper_id'    => $id,
                'created_at' => date('Y-m-d H:i:s')
            ];
            \twostagelogModel::insert($log);
        });

    }
}

